<script setup>
import {QuillEditor} from '@vueup/vue-quill';
import '@vueup/vue-quill/dist/vue-quill.snow.css';
import CodeEditor from './CodeEditor.vue';
import selector from './QuestionSelector.vue';
import {ref, reactive} from 'vue';
import {ElMessage} from 'element-plus';
import {addOjQuestionService, getOjQuestionDetailService, updateOjQuestionDetailService} from "@/api/question.js";

const visibleDrawer = ref(false);

// 定义表单数据
const formQuestion = reactive({
  id: "",
  title: "",
  difficulty: "",
  timeLimit: "",
  spaceLimit: "",
  content: "",
  questionCase: "",
  defaultCode: "",
  mainFunction: ""
});

// 时间和空间限制
const totalTimeLimit = 1000; // 单位毫秒
const totalSpaceLimit = 256 * 1024 * 1024; // 单位字节

// 定义子传父事件
const emit = defineEmits(['success', 'update'])

// 表单验证规则 -这里只验证 时间/空间限制
const rules = {
  timeLimit: [
    {required: true, message: '请输入时间限制', trigger: 'blur'},
    {
      validator: (rule, value, callback) => {
        if (value > totalTimeLimit) {
          callback(new Error(`时间限制不能超过 ${totalTimeLimit} 毫秒 ≈ 1秒`));
        } else {
          callback();
        }
      }, trigger: 'blur'
    }
  ],
  spaceLimit: [
    {required: true, message: '请输入空间限制', trigger: 'blur'},
    {
      validator: (rule, value, callback) => {
        if (value > totalSpaceLimit) {
          callback(new Error(`空间限制不能超过 ${totalSpaceLimit} 字节 ≈ 256M`));
        } else {
          callback();
        }
      }, trigger: 'blur'
    }
  ]
};

const defaultEditCode = ref()
const mainFunctionEditCode = ref()

// 控制抽屉的显示 -将所有的内容置为空
async function OnChangeVisible(id) {
  visibleDrawer.value = true
  for (const key in formQuestion) {
    if (formQuestion.hasOwnProperty(key)) {
      formQuestion[key] = '';
    }
  }
  if (id) {
    const ojQuestionDetail = await getOjQuestionDetailService(id);
    Object.assign(formQuestion, ojQuestionDetail.data)
    defaultEditCode.value.setEditorCode(formQuestion.defaultCode)
    mainFunctionEditCode.value.setEditorCode(formQuestion.mainFunction)
  }
}

// 这里验证其他表单非空判断
function validate() {
  let message = ""
  if (!formQuestion.title) {
    message = "请输入OJ题目标题"
  } else if (formQuestion.difficulty === "") {
    message = "请选择OJ题目难度"
  } else if (!formQuestion.content) {
    message = "请输入OJ题目内容"
  } else if (!formQuestion.questionCase) {
    message = "请输入OJ题目测试用例"
  } else if (!formQuestion.defaultCode) {
    message = "请输入OJ题目默认代码块"
  } else if (!formQuestion.mainFunction) {
    message = "请输入OJ题目主函数"
  } else {
    message = ""
  }
  return message
}

// 提交表单时验证
async function onSubmit() {
  // 先验证参数是否合法
  const errorMessage = validate();
  if (errorMessage) {
    ElMessage.error(errorMessage)
    return;
  }
  const formDate = new FormData();
  for (let key in formQuestion) {
    formDate.append(key, formQuestion[key])
  }
  if (formQuestion.id) {
    await updateOjQuestionDetailService(formDate)
    ElMessage.success("编辑OJ题目成功")
    emit('success')
  } else {
    await addOjQuestionService(formDate)
    ElMessage.success("新增OJ题目成功")
    emit('success')
  }
  // 关闭抽屉栏
  visibleDrawer.value = false
}

defineExpose({
  OnChangeVisible
});

// 双向绑定默认代码块
function handleEditorDefaultCode(content) {
  formQuestion.defaultCode = content
}

// 双向绑定 main函数
function handleEditorMainFunc(content) {
  formQuestion.mainFunction = content
}
</script>

<template>
  <el-drawer v-model="visibleDrawer" :destroy-on-close="true" :with-header="false" size="40%">
    <el-form :model="formQuestion" :rules="rules" ref="formRef">
      <el-form-item label="题⽬标题:" prop="title">
        <el-input style="width:387px !important" v-model="formQuestion.title" placeholder="请输⼊标题"></el-input>
      </el-form-item>
      <el-form-item label="题⽬难度:" prop="difficulty">
        <selector style="width:387px !important" v-model="formQuestion.difficulty" width="100%"
                  placeholder="请选择题⽬难度">
        </selector>
      </el-form-item>
      <el-form-item label="时间限制（单位毫秒）:" prop="timeLimit">
        <el-input style="width:300px !important" v-model="formQuestion.timeLimit"
                  placeholder="请输⼊时间限制"></el-input>
      </el-form-item>
      <el-form-item label="空间限制（单位字节）:" prop="spaceLimit">
        <el-input style="width:300px !important" v-model="formQuestion.spaceLimit"
                  placeholder="请输⼊空间限制"></el-input>
      </el-form-item>
      <el-form-item label="题⽬内容:" prop="content">
        <div class="editor">
          <quill-editor placeholder="请输⼊题⽬内容" v-model:content="formQuestion.content" content-type="html">
          </quill-editor>
        </div>
      </el-form-item>
      <el-form-item label="题⽬⽤例:" prop="questionCase">
        <el-input style="width:387px !important" v-model="formQuestion.questionCase"
                  placeholder="请输⼊题⽬⽤例"></el-input>
      </el-form-item>
      <el-form-item prop="defaultCode">
        <div class="section-title">默认代码块:</div>
        <CodeEditor @update:modelValue="handleEditorDefaultCode" ref="defaultEditCode"></CodeEditor>
        <div class="item-divider"></div>
      </el-form-item>
      <el-form-item prop="mainFunction">
        <div class="section-title">main函数:</div>
        <CodeEditor @update:modelValue="handleEditorMainFunc" ref="mainFunctionEditCode"></CodeEditor>
        <div class="item-divider"></div>
      </el-form-item>
      <el-form-item>
        <div class="button-container">
          <el-button class="question-button" type="primary" plain @click="onSubmit">完成</el-button>
        </div>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>

<style lang="scss" scoped>
.question-button {
  width: 200px;
  height: 48px;
  font-size: 16px;
  font-weight: bold;
  color: #fff;
  background-color: #86bcf4;
  border: none;
  border-radius: 24px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  transition: all 0.3s ease;

  &:hover {
    background-color: #6cb1f8; /* 悬停时更亮的蓝色 */
    box-shadow: 0 6px 12px rgba(0, 0, 0, 0.3); /* 增强悬停阴影 */
    transform: translateY(-2px); /* 悬停时轻微上浮 */
  }

  &:active {
    background-color: #3a8ee6;
    transform: translateY(0);
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  }
}

.button-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  width: 100%;
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  color: #000307;
  margin-bottom: 2px;
  display: inline-block;
}

.item-divider {
  width: 100%;
  height: 1px;
  background-color: #e5e5e5;
  margin: 3px 0;
}
</style>
